<!-- 广告管理 -->
<script setup lang="ts">
defineOptions({
  name: "User",
  inheritAttrs: false,
});

import {
  getAdPage,
  updateAd,
  deleteAd,
  downloadTemplateAppApi,
  exportAd,
  getCarUserPage,
} from "@/api/ad";
import { getDeptOptions } from "@/api/dept";
import { getRoleOptions } from "@/api/role";

import { AdForm, AdQuery, AdPageVO } from "@/api/ad/types";
import { UserForm, UserQuery, UserPageVO } from "@/api/user/types";
import type { UploadInstance } from "element-plus";
import { genFileId } from "element-plus";
import Editor from "@/components/WangEditor/index.vue";
import MultiUpload from "@/components/Upload/MultiUpload.vue";
import { readConfigFile } from "typescript";
import { reactive, computed, ComputedRef } from "vue";
import { regionData, codeToText } from "element-china-area-data";
import AMapLoader from "@amap/amap-jsapi-loader";
import { onMounted, onUnmounted, ref } from "vue";

const queryFormRef = ref(ElForm); // 查询表单
const adFormRef = ref(ElForm); // 广告表单
const uploadRef = ref<UploadInstance>(); // 上传组件
const dateTimeRange = ref("");
const info = ref("");

const dateDagTimeRange = ref<any>([]);

const loading = ref(false); //  加载状态
const removeIds = ref([]); // 删除广告ID集合 用于批量删除
const userIds = ref([]);
const queryParams = reactive<AdQuery>({
  pageNum: 1,
  pageSize: 10,
});

const queryParamsUser = reactive<UserQuery>({
  pageNum: 1,
  pageSize: 10,
  type: "2",
});
const total = ref(0); // 数据总数
const totalUser = ref(0); // 数据总数
const pageData = ref<AdPageVO[]>(); // 广告分页数据
const deptList = ref<OptionType[]>(); // 部门下拉数据源
const roleList = ref<OptionType[]>(); // 角色下拉数据源
const pageUserData = ref<UserPageVO[]>(); // 广告分页数据

const listData = ref([""]);
const showViewer = ref(false);

function getImg(imgUrl: any) {
  listData.value = [];
  listData.value.push(imgUrl);
  showViewer.value = true;
}

function closeViewer() {
  showViewer.value = false;
}

watch(dateTimeRange, (newVal) => {
  if (newVal) {
    queryParams.startTime = newVal[0];
    queryParams.endTime = newVal[1];
  } else {
    queryParams.startTime = "";
    queryParams.endTime = "";
  }
});

// 弹窗对象
const dialog = reactive({
  visible: false,
  type: "user-form",
  width: 800,
  title: "",
  zIndex: 100,
});

const dialogUser = reactive({
  userVisible: false,
  width: 800,
  title: "查询用户",
  zIndex: 100,
});

const dialogMap = reactive({
  visible: false,
  type: "user-form",
  width: 800,
  title: "",
  zIndex: 200,
});

// 广告表单数据
const formData = reactive<AdForm>({
  status: "1",
  area: "",
  city: "",
  province: "",
  userId: "",
  adDesc: "",
});

const formUserData = reactive<AdForm>({
  status: "1",
});

const positionInput = ref("");

const lat = ref("");

const opType = ref(0);
// 广告导入数据
const importData = reactive({
  deptId: undefined,
  file: undefined,
  fileList: [],
});

// 校验规则
const rules = reactive({
  username: [{ required: true, message: "广告名不能为空", trigger: "blur" }],
  nickname: [{ required: true, message: "广告昵称不能为空", trigger: "blur" }],
  deptId: [{ required: true, message: "所属部门不能为空", trigger: "blur" }],
  roleIds: [{ required: true, message: "广告角色不能为空", trigger: "blur" }],
  email: [
    {
      pattern: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,
      message: "请输入正确的邮箱地址",
      trigger: "blur",
    },
  ],
  mobile: [
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  getAdPage(queryParams)
    .then(({ data }) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

function handleUserQuery() {
  getCarUserPage(queryParamsUser)
    .then(({ data }) => {
      pageUserData.value = data.list;
      totalUser.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  dateTimeRange.value = "";
  queryParams.pageNum = 1;
  queryParams.startTime = undefined;
  queryParams.endTime = undefined;
  handleQuery();
}

/** 行选中 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.adId);
}

function handleSelectionUserChange(selection: any) {
  userIds.value = selection.map((item: any) => {
    item.userId;
    formData.loginName = item.loginName;
    formData.nickName = item.nickName;
  });
  if (userIds.value.length != 1) {
    ElMessage.warning("请选择一条数据！");
    return;
  }
  formData.userId = userIds.value[0];
}

/** 加载角色下拉数据源 */
async function loadRoleOptions() {
  getRoleOptions().then((response) => {
    roleList.value = response.data;
  });
}

/** 加载部门下拉数据源 */
async function loadDeptOptions() {
  getDeptOptions().then((response) => {
    deptList.value = response.data;
  });
}

/**
 * 打开弹窗
 *
 * @param id 广告ID
 */
async function openDialog(type: any, row?: any) {
  dialog.visible = true;
  // 广告表单弹窗
  await loadDeptOptions();
  await loadRoleOptions();
  dialog.width = 800;
  if (row != undefined && row.adId != null) {
    if (type == "add-sp") {
      opType.value = 0;
    } else {
      opType.value = 1;
    }
    dialog.title = "广告维护";
    dateDagTimeRange.value = [];
    dateDagTimeRange.value.push(row.adStartDate);
    dateDagTimeRange.value.push(row.adEndDate);
    Object.assign(formData, { ...row });
    Object.assign(formUserData, { ...row.carUser });
  } else {
    formData.adContent = "";
    formData.adImg = "";
    formData.province = "";
    formData.city = "";
    formData.area = "";
    formUserData.loginName = "";
    formUserData.nickName = "";
    formData.adId = "";
    formData.userId = "";
    formData.adDesc = "";
    dateDagTimeRange.value = [];

    dialog.title = "新增广告";
  }
}

/**
 * 关闭弹窗
 * @param type 弹窗类型  广告表单：user-form | 广告导入：user-import
 */
function closeDialog() {
  dialog.visible = false;
  if (dialog.type === "user-form") {
    adFormRef.value.resetFields();
    adFormRef.value.clearValidate();
    formData.id = undefined;
    formData.status = "1";
  } else if (dialog.type === "user-import") {
    importData.file = undefined;
    importData.fileList = [];
  }
}

function closeMapDialog() {
  dialogMap.visible = false;
}

function confirmMap() {
  formData.longitude = jd.value;
  formData.latitude = wd.value;
  dialogMap.visible = false;
}

function closeUserDialog() {
  dialogUser.userVisible = false;
}

function confirmUser() {
  if (userIds.value.length != 1) {
    ElMessage.warning("请选择一条数据！");
    return;
  }
  formData.userId = userIds.value[0];
  dialogUser.userVisible = false;
}

const prop = withDefaults(
  defineProps<{
    gap: string | number; //选择框中间间隙
    width: string | number; //选择框宽度
  }>(),
  {
    gap: "8",
    width: "210",
  }
);
//抛出地址
const emit = defineEmits<{
  (
    e: "getAddress",
    data: {
      code: string[]; //区域码
      name: string[]; //汉字
      isComplete: boolean; //是否选择完整，方便校验
    }
  ): void;
}>();
let address = reactive<{
  province: string;
  city: string;
  area: string;
}>({
  province: "",
  city: "",
  area: "",
});
interface AreaList {
  value: string;
  label: string;
  children?: AreaList[];
}

let adr = ref("");
let jd = ref("");
let wd = ref("");
//切换省份函数
const handleProvinceSelect = () => {
  formData.city = "";
  formData.area = "";
  if (formData.province != undefined) {
    emit("getAddress", {
      code: [formData.province], //区域码
      name: [codeToText[formData.province]], //汉字
      isComplete: false,
    });
  }
};
//切换城市函数
const handleCitySelect = () => {
  if (
    formData.province != undefined &&
    formData.city != undefined &&
    formData.area != undefined
  ) {
    formData.area = "";
    emit("getAddress", {
      code: [formData.province, formData.city], //区域码
      name: [codeToText[formData.province], codeToText[formData.city]], //汉字
      isComplete: areaList.value.length == 0 ? true : false,
    });
  }
};
//切换地区函数
const handleAreaSelect = () => {
  if (
    formData.province != undefined &&
    formData.city != undefined &&
    formData.area != undefined
  ) {
    emit("getAddress", {
      code: [formData.province, formData.city, formData.area], //区域码
      name: [
        codeToText[formData.province],
        codeToText[formData.city],
        codeToText[formData.area],
      ], //汉字
      isComplete: true,
    });
  }
};
//二级城市列表
//const cityList: ComputedRef<AreaList[]> = computed((): AreaList[] => {

const cityList: ComputedRef<AreaList[]> = computed((): AreaList[] => {
  let temp: any = [];
  if (!formData.province) {
    return [];
  }
  temp = regionData.find((item: any) => {
    return item.label == formData.province;
  });
  if (temp != undefined && temp.children != undefined) {
    return temp.children ? temp.children : [];
  } else {
    return [];
  }
});
//三级地区列表
const areaList: ComputedRef<AreaList[]> = computed((): AreaList[] => {
  if (!formData.province || !formData.city) {
    return [];
  }
  if (cityList.value.length == 0) {
    return [];
  } else {
    let temp = cityList.value.find((item: any) => {
      return item.label == formData.city;
    });
    if (temp) {
      return temp.children ? temp.children : [];
    } else {
      return [];
    }
  }
});

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  adFormRef.value.validate((valid: any) => {
    if (valid) {
      const adId = formData.adId;
      loading.value = true;
      if (adId) {
        if (opType.value == 0) {
          formData.status = "2";
        } else {
          formData.status = "3";
        }
        updateAd(formData)
          .then(() => {
            ElMessage.success("修改广告成功");
            closeDialog();
            resetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        if (opType.value == 0) {
          formData.status = "1";
        } else {
          formData.status = "2";
        }
        updateAd(formData)
          .then(() => {
            ElMessage.success("新增广告成功");
            closeDialog();
            resetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 3000);

const openMap = useThrottleFn(() => {
  dialogMap.visible = true;
  initMap();
}, 3000);

const openUser = useThrottleFn(() => {
  dialogUser.userVisible = true;
  handleUserQuery();
}, 3000);

watch(dateDagTimeRange, (newVal) => {
  if (newVal) {
    formData.adStartDate = newVal[0];
    formData.adEndDate = newVal[1];
  }
});

/** 删除广告 */
function handleDelete(id?: number) {
  const adIds = [id || removeIds.value].join(",");
  if (!adIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除广告?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    deleteAd(adIds).then(() => {
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}

function initMap() {
  // window._AMapSecurityConfig = {
  //   securityJsCode: "1e80f235108be410e762245a76171282", // 密钥
  // }; // 重要！
  AMapLoader.load({
    key: "52278c00c9bec6fbb38b1d39d2a248b4", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ["AMap.AutoComplete", "AMap.PlaceSearch", "AMap.Geocoder"], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
  }).then((AMap) => {
    var map = new AMap.Map("container", {
      resizeEnable: true,
    });

    //输入提示
    var autoOptions = {
      input: "tipinput",
    };

    var auto = new AMap.AutoComplete(autoOptions);
    var placeSearch = new AMap.PlaceSearch({
      map: map,
    });

    auto.on("select", select);
    function select(e: any) {
      placeSearch.setCity(e.poi.adcode);
      placeSearch.search(e.poi.name);
      info.value = "";
    }
    var geocoder = new AMap.Geocoder({
      city: "全国",
    });

    map.on("click", function (e: any) {
      info.value = e.lnglat.getLng() + "," + e.lnglat.getLat();
      jd.value = e.lnglat.getLng();
      wd.value = e.lnglat.getLat();
      geocoder.getAddress(
        [e.lnglat.lng, e.lnglat.lat],
        function (status: any, result: any) {
          if (status === "complete" && result.info === "OK") {
            adr.value = result.regeocode.formattedAddress;
          }
        }
      );
    });
  });
}

/** Excel文件 Change */
function handleFileChange(file: any) {
  importData.file = file.raw;
}

function clickChange(row: any) {
  formData.userId = row.userId;
  formData.loginName = row.loginName;
}
/** Excel文件 Exceed  */
function handleFileExceed(files: any) {
  uploadRef.value!.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  uploadRef.value!.handleStart(file);
  importData.file = file;
}

/** 导出用户 */
function handleExport() {
  exportAd(queryParams).then((response: any) => {
    const fileData = response.data;
    const fileName = decodeURI(
      response.headers["content-disposition"].split(";")[1].split("=")[1]
    );
    const fileType =
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";

    const blob = new Blob([fileData], { type: fileType });
    const downloadUrl = window.URL.createObjectURL(blob);

    const downloadLink = document.createElement("a");
    downloadLink.href = downloadUrl;
    downloadLink.download = fileName;

    document.body.appendChild(downloadLink);
    downloadLink.click();

    document.body.removeChild(downloadLink);
    window.URL.revokeObjectURL(downloadUrl);
  });
}

/** 下载导入模板 */
function downloadTemplate() {
  downloadTemplateAppApi().then((response: any) => {
    const fileData = response.data;
    const fileName = decodeURI(
      response.headers["content-disposition"].split(";")[1].split("=")[1]
    );
    const fileType =
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";

    const blob = new Blob([fileData], { type: fileType });
    const downloadUrl = window.URL.createObjectURL(blob);

    const downloadLink = document.createElement("a");
    downloadLink.href = downloadUrl;
    downloadLink.download = fileName;

    document.body.appendChild(downloadLink);
    downloadLink.click();

    document.body.removeChild(downloadLink);
    window.URL.revokeObjectURL(downloadUrl);
  });
}

function handleSuccess(response: any, file: any, fileList: any) {
  ElMessage.success(response.data);
}

onMounted(() => {
  handleQuery();
});
</script>

<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 广告列表 -->
      <el-col :lg="24" :xs="24">
        <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="关键字" prop="keywords">
              <el-input
                v-model="queryParams.keywords"
                placeholder="用户名/昵称/手机号"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item label="状态" prop="status">
              <el-select
                v-model="queryParams.status"
                placeholder="全部"
                clearable
                class="!w-[100px]"
              >
                <el-option label="全部" value="" />
                <el-option label="待联系" value="0" />
                <el-option label="联系中" value="1" />
                <el-option label="投放中" value="2" />
                <el-option label="投放结束" value="3" />
              </el-select>
            </el-form-item>

            <el-form-item label="创建时间">
              <el-date-picker
                class="!w-[240px]"
                v-model="dateTimeRange"
                type="daterange"
                range-separator="~"
                start-placeholder="开始时间"
                end-placeholder="截止时间"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleQuery"
                ><i-ep-search />搜索</el-button
              >
              <el-button @click="resetQuery">
                <i-ep-refresh />
                重置</el-button
              >
            </el-form-item>
          </el-form>
        </div>

        <el-image-viewer
          v-if="showViewer"
          :z-index="10000"
          @close="closeViewer"
          :url-list="listData"
        />

        <el-card shadow="never" class="table-container">
          <template #header>
            <div class="flex justify-between">
              <div>
                <el-button
                  v-hasPerm="['sys:user:add']"
                  type="success"
                  @click="openDialog('add-form')"
                  ><i-ep-plus />新增</el-button
                >
                <el-button
                  v-hasPerm="['sys:user:delete']"
                  type="danger"
                  :disabled="removeIds.length === 0"
                  @click="handleDelete()"
                  ><i-ep-delete />删除</el-button
                >
              </div>

              <div>
                <el-dropdown split-button>
                  导入
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="downloadTemplate">
                        <i-ep-download />下载模板</el-dropdown-item
                      >
                      <el-dropdown-item>
                        <i-ep-top />
                        <el-upload
                          ref="uploadRef"
                          style="height: 30px"
                          action="/dev-api/api/car/ad/impAd"
                          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                          :limit="1"
                          :auto-upload="true"
                          :file-list="importData.fileList"
                          :on-change="handleFileChange"
                          :on-exceed="handleFileExceed"
                          :on-success="handleSuccess"
                        >
                          <div style="margin-top: 5px">导入数据</div>
                        </el-upload>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
                <el-button class="ml-3" @click="handleExport"
                  ><template #icon><i-ep-download /></template>导出</el-button
                >
              </div>
            </div>
          </template>

          <el-table
            v-loading="loading"
            :data="pageData"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column
              key="id"
              label="编号"
              type="index"
              align="center"
              width="100"
            />
            <el-table-column
              key="username"
              label="用户名"
              align="center"
              prop="carUser.loginName"
            />
            <el-table-column
              label="用户昵称"
              align="center"
              prop="carUser.nickName"
            />
            <el-table-column label="头像" align="center" width="120">
              <template #default="scope">
                <span v-if="scope.row.carUser != null"
                  ><img
                    :src="scope.row.carUser.headImg"
                    style="height: 60px"
                    @click="getImg(scope.row.carUser.headImg)"
                /></span>
              </template>
            </el-table-column>

            <el-table-column label="电话" align="center" prop="telephone" />
            <el-table-column label="微信" align="center" prop="weChat" />

            <el-table-column
              label="车主认证"
              align="center"
              prop="carAuthBrand"
            />
            <el-table-column
              label="广告描述"
              align="center"
              prop="adDesc"
              width="200"
              :show-overflow-tooltip="true"
            />

            <el-table-column label="状态" align="center" prop="status">
              <template #default="scope">
                <span v-if="scope.row.status == 0"> 待投放 </span>
                <span v-if="scope.row.status == 1"> 联系中 </span>
                <span v-if="scope.row.status == 2"> 投放中 </span>
                <span v-if="scope.row.status == 3"> 投放结束 </span>
              </template>
            </el-table-column>

            <el-table-column
              label="投放开始日期"
              align="center"
              prop="adStartDate"
            />

            <el-table-column
              label="投放结束日期"
              align="center"
              prop="adEndDate"
            />

            <el-table-column label="投放省" align="center" prop="province" />

            <el-table-column label="投放市" align="center" prop="city" />

            <el-table-column label="投放区" align="center" prop="area" />

            <el-table-column label="操作" align="center">
              <template #default="scope">
                <span v-if="scope.row.status == 0">区域投放</span>
                <span v-if="scope.row.status == 1">附近投放</span>
              </template>
            </el-table-column>

            <el-table-column label="浏览量" align="center" prop="totalLikes" />

            <el-table-column
              label="浏览人次"
              align="center"
              prop="countLikes"
            />

            <el-table-column label="操作" align="center">
              <template #default="scope">
                <el-button
                  v-if="scope.row.status == 0"
                  v-hasPerm="['sys:user:edit']"
                  type="primary"
                  link
                  size="small"
                  @click="openDialog('add-sp', scope.row)"
                  ><i-ep-edit />投放</el-button
                >

                <el-button
                  v-if="scope.row.status == 1"
                  v-hasPerm="['sys:user:edit']"
                  type="primary"
                  link
                  size="small"
                  @click="openDialog('ad-Over', scope.row)"
                  ><i-ep-edit />完成</el-button
                >

                <el-button
                  v-if="scope.row.status == 2"
                  v-hasPerm="['sys:user:edit']"
                  type="primary"
                  link
                  size="small"
                  @click="openDialog('ad-Over', scope.row)"
                  ><i-ep-view />完成</el-button
                >
                <el-button
                  v-if="scope.row.status == 3"
                  v-hasPerm="['sys:user:edit']"
                  type="primary"
                  link
                  size="small"
                  @click="openDialog('ad-Over', scope.row)"
                  ><i-ep-edit />查看</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
        </el-card>
      </el-col>
    </el-row>
    <!-- 弹窗 -->
    <el-dialog
      v-model="dialogMap.visible"
      :title="dialogMap.title"
      :width="dialogMap.width"
      height="500px"
      :z-index="dialogMap.zIndex"
      top="20%"
      append-to-body
      @close="closeMapDialog"
    >
      <div style="height: 500px">
        <div
          id="container"
          class="gdmap-container"
          style="position: absolute"
        ></div>
        <div id="myPageTop">
          <table>
            <tr>
              <td>
                <label>请输入关键字：</label>
              </td>
            </tr>
            <tr>
              <td>
                <input
                  id="tipinput"
                  v-model="adr"
                  style="border: 1px solid #f5f5f5; height: 30px; margin: 5px"
                />

                <input
                  id="info"
                  v-model="info"
                  style="border: 1px solid #f5f5f5; height: 30px; margin: 5px"
                />
                <el-button @click="confirmMap">确 定</el-button>
                <el-button @click="dialogMap.visible = false">取 消</el-button>
              </td>
            </tr>
          </table>
        </div>
      </div>
    </el-dialog>

    <!-- 弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      :z-index="dialog.zIndex"
      @close="closeDialog"
    >
      <!-- 广告新增/编辑表单 -->
      <el-form
        v-if="dialog.type === 'user-form'"
        ref="adFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="loginName">
          <el-input
            v-model="formData.loginName"
            placeholder="请选择用户"
            readonly
            @click.stop="openUser"
          />
          <i-ep-search
            style="position: absolute; margin-left: 95%"
            @click.stop="openUser"
          />
          <!-- <el-select v-model="formData.userId" placeholder="请选择">
            <el-option
              v-for="item in pageUserData"
              :key="item.loginName + ' ' + item.nickName"
              :label="item.loginName + ' ' + item.nickName"
              value="item.userId"
            />
          </el-select> -->
        </el-form-item>

        <el-form-item label="用户昵称" prop="nickName">
          <el-input
            v-model="formData.nickName"
            placeholder="请输入用户昵称"
            readonly
          />
        </el-form-item>

        <el-form-item label="投放方式" prop="nickName">
          <el-select
            v-model="formData.type"
            placeholder="全部"
            clearable
            class="!w-[100px]"
          >
            <el-option label="区域投放" value="0" />
            <el-option label="附近投放" value="1" />
          </el-select>
        </el-form-item>

        <el-form-item
          label="投放范围"
          prop="nickName"
          v-if="formData.type == 1"
        >
          <el-select
            v-model="formData.ranges"
            placeholder="全部"
            clearable
            class="!w-[100px]"
          >
            <el-option label="3公里" value="3" />
            <el-option label="5公里" value="5" />
            <el-option label="10公里" value="10" />
            <el-option label="20公里" value="20" />
            <el-option label="50公里" value="50" />
            <el-option label="100公里" value="100" />
          </el-select>
        </el-form-item>
        <el-form-item label="经纬度" prop="nickName" v-if="formData.type == 1">
          <el-input
            v-model="formData.longitude"
            style="width: 200px"
            placeholder="请输入经度"
          />
          <span style="text-align: center; width: 50px">--</span>
          <el-input
            v-model="formData.latitude"
            style="width: 200px"
            placeholder="请输入维度"
          />
          <el-button style="margin-left: 20px" @click="openMap"
            >选择中心点</el-button
          >
        </el-form-item>

        <el-form-item
          label="投放区域"
          prop="nickName"
          v-if="formData.type == 0"
        >
          <div class="areabox" v-if="formData.type == 0">
            <el-select
              v-model="formData.province"
              placeholder="请选择省"
              :style="{
                width: `${prop.width}px`,
                marginRight: `${prop.gap}px`,
              }"
              @change="handleProvinceSelect"
            >
              <el-option
                v-for="item in regionData"
                :label="item.label"
                :value="item.label"
              />
            </el-select>
            <el-select
              v-if="formData.type == 0"
              v-model="formData.city"
              placeholder="请选择市"
              :disabled="!formData.province || cityList.length == 0"
              :style="{
                width: `${prop.width}px`,
                marginRight: `${prop.gap}px`,
              }"
              @change="handleCitySelect"
            >
              <el-option
                v-for="item in cityList"
                :label="item.label"
                :value="item.label"
              />
            </el-select>
            <el-select
              v-if="formData.type == 0"
              v-model="formData.area"
              placeholder="请选择区"
              :style="{ width: `${prop.width}px` }"
              :disabled="
                !formData.province || !formData.city || areaList.length == 0
              "
              @change="handleAreaSelect"
            >
              <el-option
                v-for="item in areaList"
                :label="item.label"
                :value="item.label"
              />
            </el-select>
          </div>
        </el-form-item>

        <el-form-item label="投放时间" prop="nickName">
          <el-date-picker
            class="!w-[240px]"
            v-model="dateDagTimeRange"
            type="daterange"
            range-separator="~"
            start-placeholder="开始时间"
            end-placeholder="截止时间"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="广告描述">
          <el-input type="textarea" v-model="formData.adDesc" />
        </el-form-item>
        <el-form-item label="广告内容">
          <editor v-model="formData.adContent" style="height: 400px" />
        </el-form-item>

        <el-form-item label="广告主图" style="height: 200px">
          <single-upload v-model="formData.adImg" />
        </el-form-item>
      </el-form>

      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="dialogUser.userVisible"
      :title="dialogUser.title"
      :width="dialogUser.width"
      :append-to-body="true"
      @close="closeUserDialog"
    >
      <!-- 广告新增/编辑表单 -->
      <el-form
        v-if="dialog.type === 'user-form'"
        ref="adFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item>
          <el-input
            v-model="queryParamsUser.keywords"
            placeholder="用户名/昵称/手机号"
            clearable
            style="width: 200px"
          />
          <el-button
            type="primary"
            @click="handleUserQuery"
            style="margin-left: 100px"
            ><i-ep-search />搜索</el-button
          >
        </el-form-item>
        <el-table
          v-loading="loading"
          :data="pageUserData"
          :height="800"
          @selection-change="handleSelectionUserChange"
        >
          <el-table-column type="selection" width="50" align="center" />

          <!-- <el-table-column label="选择" width="100" align="center">
            <template #default="scope">
              <el-radio @input="clickChange(scope.row)"></el-radio>
            </template>
          </el-table-column> -->

          <el-table-column
            key="id"
            label="编号"
            type="index"
            align="center"
            width="100"
          />

          <el-table-column
            key="id"
            label="用户编号"
            prop="userId"
            align="center"
            width="100"
          />
          <el-table-column
            key="loginName"
            label="用户名"
            align="center"
            prop="loginName"
          />
          <el-table-column label="用户昵称" align="center" prop="nickName" />
          <el-table-column label="头像" align="center" width="120">
            <template #default="scope">
              <span v-if="scope.row.headImg != null"
                ><img
                  :src="scope.row.headImg"
                  style="height: 60px"
                  @click="getImg(scope.row.headImg)"
              /></span>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-if="totalUser > 0"
          v-model:total="totalUser"
          v-model:page="queryParamsUser.pageNum"
          v-model:limit="queryParamsUser.pageSize"
          @pagination="handleUserQuery"
        />
      </el-form>
      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirmUser">确 定</el-button>
          <el-button @click="dialogUser.userVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped>
@import "https://cache.amap.com/lbs/static/main1119.css";
.gdmap-container {
  width: 500px;
  height: 300px;
}
#container {
  padding: 0px;
  margin: 0px;
  border: 1px solid gray;
  width: 100%;
  height: 100%;
}
</style>
